﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Creature : MonoBehaviour
{
    public CreateSenceCreature ServerData;
    public CreatureDatabase TableData;

    //血量变化监听<当前血量，最大血量>
    public event Action<int, int> HPChangedCallback;

    public Creature CurTarget;//当前目标
    //角色的短暂记忆，目标点
    protected Purpose _purpose;
    //移动管理
    protected NavMeshAgent _agent;
    //动画管理
    protected Animator _animator;
    //技能管理
    protected SkillMgr _skillMgr = new SkillMgr();
    //当前状态
    protected CreatureState CurState = CreatureState.Idle;
    
    public int ThisId { get { return ServerData.ThisID; } }
    public string Name { get { return ServerData.Name; } }
    public string ModelPath { get { return TableData.ModelPath; } }
    public GameObject CenterPoint { get; protected set; }

    public Vector3 Position { get { return transform.position; } }

    public bool IsCastingSkill { get { return _skillMgr.IsCastingSkill; } }

    public bool IsAlive { get { return CreatureState.Die != CurState; } }

    public bool CanMove { get { return IsAlive && !IsCastingSkill;  } }

    public bool CanCastSkill { get { return IsAlive && !IsCastingSkill; } }

    public bool IsAssistOrCastingSkill { get { return _skillMgr.IsAssistOrCastingSkill; } }

    private Vector3 _hitPoint;
    public Vector3 HitPoint { get { return _hitPoint; } }
    public int HP
    {
        
        get { return ServerData.HP; }
        set
        {
            var newHp = Math.Max(0, value);
            var oldHp = ServerData.HP;
            ServerData.HP = newHp;
            //死亡：血量从非零到零的过程
            if (ServerData.HP <= 0 && oldHp > 0)
            {
                //死亡
                onDie();
            }
            //重生：血量 零-->非零
            if (oldHp <= 0 && ServerData.HP > 0)
            {
                OnResqawn();
            }
            //Debug.Log(HP);
            if (HPChangedCallback != null) { HPChangedCallback(value, ServerData.MaxHP); }
        }
    }
    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="服务器数据"></param>
    /// <param name="配置表数据"></param>
    public virtual void Init(CreateSenceCreature serverData, CreatureDatabase tableData)
    {
        ServerData = serverData;
        TableData = tableData;
        initMountPoint();
        _agent = gameObject.AddComponent<NavMeshAgent>();
        _animator = GetComponent<Animator>();

        _agent.stoppingDistance = GameSetting.StopDistance;//在距目标位置的这一距离内停止
        _agent.speed = 10f;
        _agent.angularSpeed = float.MaxValue;
        _agent.acceleration = float.MaxValue;
        _agent.obstacleAvoidanceType = ObstacleAvoidanceType.NoObstacleAvoidance;
        //初始化

        _skillMgr.Init(this);
    }

    protected virtual  void initMountPoint()
    {
        var hitPoint = gameObject.Find<Transform>("HitPoint").transform.position;
        if (hitPoint == null)
        {
            Debug.LogError("没有找到打击点"+Name);
            return;
        }
        _hitPoint=hitPoint;
       
    }

    public void LookAt(Creature target)
    {
        var realWatchPos = new Vector3(target.transform.position.x, transform.position.y, target.transform.position.z);
        transform.LookAt(realWatchPos);
    }

    //寻路到某个点
    public void PathTo(Vector3 target)
    {
        if (!CanMove) { return; }
       
        _agent.SetDestination(target);
        SetState(CreatureState.Move);
        SetAnim(1);
    }
    
    public virtual bool CanBeAttack(Creature attacker)
    {
        //活着
        return IsAlive;
      
    }

    //重置目标
    private void resetPurpose()
    {
        _purpose = null;
    }

    public void StopMove()
    {
        _agent.Stop();
        _agent.ResetPath();
        //SetAnim(0);
        if (CurState == CreatureState.Move)
        {
            SetState(CreatureState.Idle);
        }
        resetPurpose();
    }
    public void SetState(CreatureState newState)
    {
        CurState = newState;
        SetAnim((int)CurState);
    }
    public CreatureState GetState()
    {
        return CurState;
    }
    protected virtual void OnResqawn()
    {
        Debug.Log("重生");
        SetState(CreatureState.Resqawn);
        TimerMgr.GetInstance().CreateTimerAndStart(1.2f, 1, () =>
        {
            if (GetState() == CreatureState.Resqawn)
            {
                SetState(CreatureState.Idle);
            }
        });
    }
    protected virtual void onDie()
    {
        Debug.Log("死亡");
        StopMove();
        SetState(CreatureState.Die);
        TimerMgr.GetInstance().CreateTimerAndStart(5, 1, () => HP = ServerData.MaxHP);
    }
    public void SetAnim(int motionType)
    {
        _animator.SetInteger("MotionType", motionType);
    }
    public int GetAnim()
    {
        return _animator.GetInteger("MotionType");
    }

    public void PurposeTo(Vector3 target, float stopDistance = -1, Action arrivedCallback = null)
    {
        //判断技能直接return
        if (!CanMove) { return; }
        if (stopDistance < 0)
        {
            stopDistance = GameSetting.StopDistance;
        }
        resetPurpose();
        if (Util.Distance2_5D(transform.position, target) < stopDistance)
        {
            if (arrivedCallback != null) { arrivedCallback(); }
            return;
        }
        var _purpose = new Purpose();
        _purpose.TargetPos = target;
        _purpose.StopDistance = stopDistance;
        _purpose.Callback = arrivedCallback;

        PathTo(_purpose.TargetPos);
    }
    //追踪到
    public void TranceTo(Creature target,float stopDistance=-1,Action arrivedCallback = null)
    {
        if (!CanMove) { return; }
        var purposeTrace = new PurposeTrace();
        purposeTrace.Owner = this;
        purposeTrace.Init(target, stopDistance, arrivedCallback);
        _purpose = purposeTrace;
        PathTo(purposeTrace.TargetPos);
    }
    //释放技能 
    public virtual void CastSkill(int index)
    {
        if (!CanCastSkill) { return; }
        _skillMgr.TryCastSkill(index);
    }
    //获取技能CD百分比
    protected float getSkillCDPercent(int index)
    {
        return _skillMgr.getSkillCDPercent(index);
    }


    protected virtual void Update()
    {
        runLoop();
        if (_purpose == null) { return; }
        var dis = Util.Distance2_5D(transform.position, _purpose.TargetPos);

        if (dis < _purpose.StopDistance)
        {
            onArrived();
            return;
        }
        //驱动目标
        _purpose.Loop();

    }

    private void runLoop()
    {
        _skillMgr.Loop();
    }

    private void onArrived()
    {
        doPurpos();
        StopMove();
    }

    private void doPurpos()
    {
        if (_purpose != null)
        {
            if (_purpose.Callback != null) { _purpose.Callback(); }
            resetPurpose();
        }
    }

    //生命体逻辑状态
    public enum CreatureState 
    {
        None=-1,
        Idle=0,
        Move=1,
        Die=2,
        Resqawn=3,

        Attack =10,
    }

}
